package com.kit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

/**
 * 图片压缩<br>
 * 必须只能单进程单线程操作
 * 
 * @author Yuanqy
 *
 */
public class ImgCutKit {
	static Long SIZE = 1024L * 1024L;// 1M
	static Long ACOUNT = 0L;
	static Long AFOLDE = 0L;
	static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

	/**
	 * <code> java ImgTools /webapps/img/imgs/roomRegister 500 > ImgTools.out &
	 * <code>
	 */
	public static void main(String[] args) {
		if (args.length < 2)
			LOG("java ImgTools 图片所在文件夹  图片压缩尺寸kb  [图片转移目录(不写即覆盖)]");
		String path = args[0];
		long size = Long.valueOf(args[1]) * 1024;// kb * 1024 = B
		String tarPath = null;
		if (args.length > 2)
			tarPath = args[2];
		doCut(path, size);

	}

	public static void doCut(String path, long size) {
		try {
			long t = System.currentTimeMillis();
			String tarPath = path;
			LOG("=== 开始压缩：SIZE=" + SIZE / 1024 + "kb;DIR=" + path);
			// 1.读文件
			List<File> list = readFiles(path);
			// 2.压缩图片
			reSizeImg(list, SIZE, tarPath);
			LOG("共读取文件数：" + ACOUNT + "\t文件夹数：" + AFOLDE + "\t需压缩文件数：" + list.size() + "\t总耗时:" + (System.currentTimeMillis() - t) + "ms");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 1.读文件
	 */
	private static List<File> readFiles(String path) throws FileNotFoundException {
		List<File> list = new ArrayList<>();
		File file = new File(path);
		if (!file.isDirectory()) {
			ACOUNT += 1;
			if (file.length() > 0 && file.length() > SIZE)
				list.add(file);
		} else {
			AFOLDE += 1;
			File[] files = file.listFiles();
			for (File file2 : files)
				list.addAll(readFiles(file2.getPath()));
		}
		return list;
	}

	/**
	 * 2.压缩图片,等比
	 */
	private static void reSizeImg(List<File> files, long size, String tarPath) throws IOException {
		for (int i = 0; i < files.size(); i++) {
			File file = files.get(i);
			try {
				System.out.print(SDF.format(new Date()) + " : " + "[" + i + "/" + files.size() + "],处理文件：" + file.getPath());
				long oldSize = file.length();
				if (oldSize <= size)
					continue;
				boolean check = true;
				float scale = 0.9f;
				int count = 0;
				String outPath = tarPath == null ? file.getPath() : tarPath + "/" + file.getName();
				while (check) {
					count++;
					BufferedImage src = ImageIO.read(file);
					if (src != null) {
						int deskHeight = (int) (src.getHeight(null) * scale);
						int deskWidth = (int) (src.getWidth(null) * scale);
						BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR);
						tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null);
						ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
						ImageIO.write(tag, "JPEG", byteOut);
						if (byteOut.size() > size) {
							scale = scale - 0.1f;
							continue;
						} else {
							check = !check;
						}
						saveFile(outPath, byteOut.toByteArray());
						System.out.print(",压缩率为：" + scale + ",转换次数:" + count + "\n");
					} else {
						check = !check;
					}
				}
			} catch (Exception e) {
				LOG("ERROR:" + file.getPath());
				e.printStackTrace();
			}
		}
		LOG("\n=== 压缩完成 ===");
	}

	private static void LOG(String info) {
		System.out.println(SDF.format(new Date()) + "\t: " + info);
	}

	/**
	 * 3.保存文件
	 */
	private static void saveFile(String outPath, byte[] data) throws IOException {
		FileOutputStream deskImage = new FileOutputStream(outPath); // 输出到文件流
		deskImage.write(data);
		deskImage.close();
	}
}